import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  closeWindow: (windowName: string) => {
    ipcRenderer.send('close-window', windowName)
  },
  getTodoDataList: () => {
    return ipcRenderer.invoke('getTodoDataList')
  },
  getTrashData: () => {
    return ipcRenderer.invoke('getTrashData')
  },
  deleteTrashData: (id) => {
    ipcRenderer.send('deleteTrashData', id)
  },
  restoreTrashData: (id) => {
    ipcRenderer.send('restoreTrashData', id)
  },
  addTodoData: (todoItem) => {
    ipcRenderer.send('addTodoData', todoItem)
  },
  updateTodoData: (todoItem) => {
    ipcRenderer.send('updateTodoData', todoItem)
  },
  deleteTodoData: (id) => {
    ipcRenderer.send('deleteTodoData', id)
  },
  getTodoNavList: () => {
    return ipcRenderer.invoke('getTodoNavList')
  },
  addTodoNav: () => {
    return ipcRenderer.send('addTodoNav')
  },
  deleteTodoNavData: (id) => {
    ipcRenderer.send('deleteTodoNavData', id)
  },
  addTodoNavData: (todoNavItem) => {
    ipcRenderer.send('addTodoNavData', todoNavItem)
  },
  updateTodoNavData: (todoNavItem) => {
    ipcRenderer.send('updateTodoNavData', todoNavItem)
  },
  sendTodoNavData: (todoNavItem) => {
    ipcRenderer.send('sendTodoNavData', todoNavItem)
  },
  getEditTodoNavData: () => {
    return ipcRenderer.send('getEditTodoNavData')
  },
  getNewNavData: (channel, func) => {
    return ipcRenderer.on(channel, (_, ...args) => func(...args))
  },
  todoNavAdd: (data) => {
    ipcRenderer.send('todoNavAdd', data)
  },
  getHabitDataList: () => {
    return ipcRenderer.invoke('getHabitDataList')
  },
  addHabitData: (habitItem) => {
    ipcRenderer.send('addHabitData', habitItem)
  },
  deleteHabitData: (id) => {
    ipcRenderer.send('deleteHabitData', id)
  },
  updateHabitData: (habitItem) => {
    ipcRenderer.send('updateHabitData', habitItem)
  },
  openSetting: () => {
    ipcRenderer.send('openSetting')
  },
  themeToggle: (theme) => {
    ipcRenderer.send('themeToggle', theme)
  }
  // addTodoData: (todoItem: TodoItem) => ipcRenderer.invoke('addTodoData', todoItem),
  // updateTodoData: (todoItem: TodoItem) => ipcRenderer.invoke('updateTodoData', todoItem),
  // deleteTodoData: (id: string) => ipcRenderer.invoke('deleteTodoData', id)
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
